<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.back()"
        fixed
      />
    </div>
    <div class="search-list_content">
      <!-- 上拉刷新的组件 -->
      <van-list
        v-model="loading"
        :finished="done"
        :immediate-check="false"
        finished-text="没有更多了"
        offset="50"
        @load="pullUpLoadMoreFn"
      >
        <div class="container-search" v-if="!show">
          <!-- 这里需要显示搜索结果的组件 -->
          <ArticleItem
            v-for="(item, index) in resultList"
            :key="index"
            :obj="item"
            :isShowCross="false"
          >
          </ArticleItem>
        </div>
      </van-list>
    </div>
  </div>
</template>

<script>
// 引入搜索结果接口
import { getSearchResultAPI } from '../../api/search'

import { Toast } from 'vant'
// 页码
let page = 1
export default {
  // 组件名
  name: 'SearchResult',
  data () {
    // 提高用户体验
    this.toast = Toast.loading({
      message: '加载中',
      duration: 0
    })
    return {
      show: true,
      // page: 1,
      loading: false, // 上拉刷新是否继续加载
      done: false, // 是否加载完毕
      resultList: [] // 获取搜索数据的数组
    }
  },
  // 组件激活触发的钩子函数
  async  activated () {
    // 初始化先获取一次数据
    await this.getSearchResultlist()

    // 提高用户体验
    this.show = false

    if (!this.show) {
      this.toast.clear()
    }
  },
  // 组件失去激活触发的钩子函数
  deactivated () {
    page = 1
    this.resultList = []
  },
  computed: {
    // 优化,每次加载都要从route中拿去数据耗费性能
    txt () {
      return this.$route.params.keyword
    }
  },
  methods: {

    async getSearchResultlist () {
      // 每次初始化页面前调用接口获取数据
      const res = await getSearchResultAPI({
        q: this.txt,
        page: page++
      })

      const { results } = res.data
      // console.log(results)
      if (results.length < 10) {
        this.done = true
        this.loading = false
        return
      }
      this.resultList = [...this.resultList, ...res.data.results]
      // console.log(res.data)

      this.loading = false
    },
    pullUpLoadMoreFn () {
      if (this.resultList.length > 0) {
        this.getSearchResultlist()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
